const FacebodyClient = require('@alicloud/facebody20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
const fs = require('fs');
const http = require('http');
const https = require('https');

let config = new OpenapiClient.Config({
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
config.endpoint = `facebody.cn-shanghai.aliyuncs.com`;
const client = new FacebodyClient.default(config);


// // 更新用户头像
exports.human_count = async (req, res) => {
  try {
    const { imageBinaryBase64 } = req.body; // 从请求体中获取URL
    // 将 base64 格式的 imageBinaryBase64 转换为 二进制
    const tmp = imageBinaryBase64.replace(/^data:image\/\w+;base64,/, "");
    const imageBinary = Buffer.from(tmp, 'base64');

    // 将 Buffer 写入到本地临时文件
    const tempFilePath = './DetectBodyCount.jpg';
    fs.writeFileSync(tempFilePath, imageBinary);
    //读取本地临时文件
    const fileStream = fs.createReadStream(tempFilePath);
    let detectBodyCountAdvanceRequest = new FacebodyClient.DetectBodyCountAdvanceRequest();
    detectBodyCountAdvanceRequest.imageURLObject = fileStream;
    //SDK例码
    let runtime = new TeaUtil.RuntimeOptions({});
    client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime)
    .then(function(detectBodyCountResponse){
      //console.log(detectBodyCountResponse);
      console.log(detectBodyCountResponse.body.data);
      const responseJson = detectBodyCountResponse?.body?.data;

      //发送的json内容
      res.status(200).json(
        {
          "code": 0,
          "message": "成功",
          "data": {
            "count": responseJson?.personNumber
          }
        }
      );
    },function(error){
      console.log(error);
      console.log(error.data.Code);
    })
    
  } catch (error) {
    console.error(error);
    res.status(500).send('An error occurred while processing the request.');
  }

};








